package com.kms.util;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.rmi.server.UID;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;

import org.apache.log4j.Logger;


/**
 * 全局工具类:目前主要处理文件操作封装类
 * 
 * @author zhushu
 */
public class CoreUtil {
	static Logger coreUtilLog = Logger.getLogger("com.kms.util.CoreUtil");
	public static Boolean writeStringToFile(String filepath,String fileContent){
		Boolean _r = true;
		try {
			File file  = new File(filepath);
			coreUtilLog.info("create file is '"+filepath +"'.");
			org.apache.commons.io.FileUtils.writeStringToFile(file, fileContent,"GBK");
		} catch (IOException e) {
			_r = false;
			coreUtilLog.error("create file '"+filepath+"' throws error "+e.toString());
		}
		
		return _r;
	}
	
	
	public static  Boolean forceDelete(String filepath){
		Boolean _r = true;
		File file  = new File(filepath);
		try {
			coreUtilLog.info("delete file is '"+filepath +"'.");
			org.apache.commons.io.FileUtils.forceDelete(file);
		} catch (IOException e) {
			_r = false;
			coreUtilLog.error("delete file '"+filepath+"' throws error "+e.toString() );
		}
		return _r;
	}
	
	public static List<String> getListToFile(String filepath,Object... objects){
		coreUtilLog.info("reading file '"+filepath+"' ");
		List<String> list = new ArrayList<String>();
		 org.apache.commons.io.LineIterator it = null; 
		try {
			 File file = new File(filepath);
			 if(objects.length>0){
				 it = org.apache.commons.io.FileUtils.lineIterator(file,String.valueOf(objects[0]));
			 }else{
				 it = org.apache.commons.io.FileUtils.lineIterator(file);
			 }
		   while (it.hasNext()) {
			   String s = it.nextLine();
			   if(s == null || s.length() < 2) continue;
			   list.add(s);
		   }
		 } catch (IOException e) {
			 coreUtilLog.info("reading file '"+filepath+"' error is "+e.toString());
		} finally {
			 org.apache.commons.io.LineIterator.closeQuietly(it);
		 }
		return list;
	}
	
	/**
	 * 将相同Key MAP集合的Value存入LinkedList集合
	 * @param key
	 * @param value
	 * @param mapv
	 * @return
	 */
	public static LinkedHashMap<String,LinkedList<String>> sameKeyMap(String key,String value,LinkedHashMap<String,LinkedList<String>> mapv){
		LinkedList<String> _l = null;
		if(mapv.get(key)==null){
			_l = new LinkedList<String>();
		}else{
			_l = mapv.get(key);
		}
		_l.add(value);
		mapv.put(key, _l);
		return mapv;
	} 
	public static LinkedHashMap<String,LinkedList<String>> sameKeyPropertyMap(String filedname,LinkedHashMap<String,LinkedList<String>> mapv){
		try {
			LinkedList<String> _l = null;
			String[] entityname = filedname.split("[.]");
			if(entityname.length>=2){
				if(mapv.get(entityname[0])==null){
					_l = new LinkedList<String>();
				}else{
					_l = mapv.get(entityname[0]);
				}
				_l.add(entityname[1]);
				mapv.put(entityname[0], _l);
			}
		} catch (Exception e) {
			coreUtilLog.info("CoreUtil Class LinkedHashMap method is error '"+e.toString());
		}
		return mapv;
	} 
	
	public static List<File> getFilesFromDirectory(String directory){
		ArrayList<File> fileList = new ArrayList<File>();
		try {
			File file = new File(directory);
			if( file.listFiles()==null){
				file.mkdirs();
				file = new File(directory);
			}
			if (file.isFile()) {// 是否为文件
				coreUtilLog.info("directory address is file.");
			} else {
				// 列出所有的文件及目录
				File[] files = file.listFiles();
				
				for (int i = 0; i < files.length; i++) {
					// 先列出目录
					if (files[i].isDirectory()) {// 是否为目录
						// 取得文件名
						//System.out.println("[" + files[i].getPath() + "]");
					} else {
						// 文件先存入fileList
						fileList.add(files[i]);
					}
				}
			}

		} catch (ArrayIndexOutOfBoundsException e) {
			coreUtilLog.error("using:java FileDemo pathname "+e.getMessage());
		}
		
		return fileList;
	}
	
	
	public static String makeBlank(String tag,Integer size){
		StringBuffer _sb = new StringBuffer();
		for(int i=0;i<size;i++){
			_sb.append(tag);
		}
		return _sb.toString();
	}
	
	public static String filterNUll(Object _v){
		String _s = "";
		if(_v==null || _v.equals("")){
			_s = "";
		}else{
			_s = _v+"";
		}
		return _s;
	}
//	
//	public static Map<String,String> getFileInfo(String filepath){
//		Map<String,String> rs = new HashMap<String,String>();
//		List<String> ls = CoreUtil.getListToFile(filepath,"UTF-8");
//		for(String _rs:ls){
//			String[] _s = _rs.split(GlobalPara._EQ);
//			if(_s.length==2){
//				rs.put(_s[0], _s[1]);
//			}
//		}
//		
//		return rs;
//	}
	/**
	 * 从文件末尾读取指定行数
	 * 
	 * @param filename
	 * @param charset
	 * @param lines
	 */
	public static LinkedList<String> readFileFromEndRF(String filename, String charset,int lines) {
		LinkedList<String> _rs  = new LinkedList<String>();
		RandomAccessFile rf = null;
		try {
			rf = new RandomAccessFile(filename, "r");
			long len = rf.length();
			long start = rf.getFilePointer();
			long nextend = start + len - 1;
			String line;
			rf.seek(nextend);
			int c = -1;
			int linenum = 0;
			while (nextend > start) {
				
				c = rf.read();
				if (c == '\n' || c == '\r') {
					line = rf.readLine();
					if (line != null) {
						_rs.add(new String(line.getBytes("ISO-8859-1"), charset));
						linenum=linenum+1;
					} else {
						//System.out.println(line);
					}
					nextend--;
				}
				nextend--;
				rf.seek(nextend);
				if (nextend == 0) {// 当文件指针退至文件开始处，输出第一行
					_rs.add(new String(rf.readLine()));
				}
				if(linenum==lines){
					break;
				}
			}
		} catch (Exception e) {
			coreUtilLog.error("CoreUtil readFileFromEndRF method is error '"+e.getMessage());
		} finally {
			try {
				if (rf != null)
					rf.close();
			} catch (IOException e) {
				coreUtilLog.error("CoreUtil close  RandomAccessFile  is error '"+e.getMessage());
			}
		}
		
		return _rs;
	}
//	
//	public static void removeTendaysFiles(){
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
//		String path = GlobalContainers.CONTEXTPATCH.substring(0, GlobalContainers.CONTEXTPATCH.lastIndexOf("\\"));
//		File file = new File(path+GlobalPara.FILE_PATH);
//		if( file.listFiles()==null){
//			file.mkdirs();
//			file = new File(path+"");
//		}
//		for(File fi :file.listFiles()){
//			String filename = fi.getName();
//			if(Pattern.matches("([\\w\\W]*).\\d{6}", filename)){
//				
//			}
//			if(Pattern.matches("([\\w\\W]*).\\d{6}.["+GlobalPara.SUFFIX_TAG+"]+", filename)){
//				
//			}
//		}
//	}
	
	/**
	 * 输出指定字符长度，按指定符号补位
	 * 
	 * @param _par
	 * @param length
	 * @param split
	 * @param situation H头部，T尾部
	 * @return
	 */
	public static String checkString(String value,int length,String split,String situation){
		StringBuffer _sb = new StringBuffer();
		for(int i=0;i<length;i++){
			_sb.append(split);
		}
		
		String re = "";
		
		if("H".equals(situation)){
			re = _sb.toString() + value;
			re = re.substring(re.length()-length, re.length());
		}else if("T".equals(situation)){
			re =  value + _sb.toString();
			re = re.substring(0, length);
		}
		return re;
	}
	
	public static Integer getDateToInteger(Date date){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		return Integer.parseInt(sdf.format(date));
	}
	
	public static Date getIntegerToDate(Integer date){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		try {
			return sdf.parse(date+"");
		} catch (ParseException e) {
			return new Date();
		}
	}
	
	public static String getListIntegerForInSQL(List<Integer> ints){
		StringBuffer _s = new StringBuffer("'-999',");
		for(Integer v :ints)
		{
			_s.append("'"+v+"'");
			_s.append(",");
		}
		return _s.toString().substring(0,_s.length()-1);
	}

	/**
	 * Get Integer List set Max value
	 * 
	 * @param ints
	 * @return
	 */
	public static Integer getMaxIntegerList(List<Integer> ints){
		Integer mxv = 0;
		if(ints.size()>0){
			mxv = ints.get(0);
		}
		
		for(Integer v:ints){
			if(v>mxv){
				mxv = v;
			}
		}
		
		return mxv;
	}
	public static Integer getMinIntegerList(List<Integer> ints){
		Integer mxv = 0;
		if(ints.size()>0){
			mxv = ints.get(0);
		}
		for(Integer v:ints){
			if(v<mxv){
				mxv = v;
			}
		}
		return mxv;
	}
	/**
	 * 
	 * @param startdate yyyyMMdd
	 * @param enddate yyyyMMdd
	 * @return
	 * @throws ParseException 
	 */
	public static List<Integer> getListdate(Integer startdate,Integer enddate){
		List<Integer> listdate = new ArrayList<Integer>();
		try {
			SimpleDateFormat  sdf2 = new SimpleDateFormat("yyyyMMdd");
			Date stard = sdf2.parse(startdate+"");
			Date endd = sdf2.parse(enddate+"");
			
			Calendar cal = Calendar.getInstance();
			cal.setTime(stard);
			do{
				listdate.add(Integer.valueOf(sdf2.format(cal.getTime())));
				cal.add(Calendar.DAY_OF_WEEK, 1);
			}while(endd.after(cal.getTime()) || endd.getTime()==cal.getTime().getTime());
		} catch (Exception e) {
			coreUtilLog.error("CoreUtil getListdate is error '"+e.getMessage());
		}
		return listdate;
	}
	
	public static Integer getTodayDate(String datetype){
		SimpleDateFormat  sdf2 = new SimpleDateFormat(datetype);
		return Integer.valueOf(sdf2.format(new Date()));
	}
	
	/**
	 * 对数字类型日期进行加减操作
	 * @param data
	 * @param days
	 * @return 转换异常情况返回系统当天日期
	 */
	public static Integer addIntegerDateFromDatetype(Integer date,Integer amount){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		sdf.format(date);
		Calendar calendar = Calendar.getInstance();
		try {
			calendar.setTime(sdf.parse(String.valueOf(date)));
			calendar.add(Calendar.DAY_OF_WEEK, amount);
		} catch (Exception e) {
			coreUtilLog.error("CoreUtil addIntegerDateFromDatetype method is error '"+e.getMessage());
		}
		return Integer.valueOf(sdf.format(calendar.getTime()));
	}
	/**
	 * 创建目录
	 * @param dir
	 */
	public static void Mkdir(String dir){
		try {
			org.apache.commons.io.FileUtils.forceMkdir(new File(dir));
		} catch (IOException e) {
			coreUtilLog.error("CoreUtil Mkdir method is error '"+e.getMessage());
		}
	}
	/**
	 * 删除指定目录下，amount天前的文件
	 * @param dir
	 * @param amount
	 * @throws ParseException
	 */
	public static  void deleteFromDaysFiles(String dir,int amount) throws ParseException{
		File[] fis = new File(dir).listFiles();
		Calendar calendar = Calendar.getInstance();
		for(File file:fis){
			calendar.setTimeInMillis(file.lastModified());
			calendar.add(Calendar.DAY_OF_MONTH, amount);
			if(calendar.getTime().before(new Date())){
				file.delete();
			}
		}
	}
	
	public static String getUID(){
		return new UID().toString();
	}
	
	
	public static String getUUIDJDK(){
		UUID uuid  =  UUID.randomUUID(); 
		return UUID.randomUUID().toString();
	}
	
	public String Value(Object v){
		String _r = null;
		if(v==null){
			_r = "";
		}else{
			_r = v.toString();
		}
		return _r;
	}
	
    /** 
     * 追加文件：使用RandomAccessFile 
     *  
     * @param fileName 
     *            文件名 
     * @param content 
     *            追加的内容 
     */  
    public static void addContentToFile(String fileName, String content) {  
        try {  
            // 打开一个随机访问文件流，按读写方式  
            RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");  
            // 文件长度，字节数  
            long fileLength = randomFile.length();  
            // 将写文件指针移到文件尾。  
            randomFile.seek(fileLength);  
            randomFile.writeBytes(content);  
            randomFile.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    } 
    
    public static void main(String[] args){
    	
    	CoreUtil cu = new CoreUtil();
    	for(int i=0;i<10000;i++){
    		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
    		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss");
    		String datetime = sdf.format(new Date());
    		cu.addContentToFile("d:/"+datetime+"",  sdf2.format(new Date())+"         ddd\n");
    		try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
			}
    	}
    }
}
